var express = require('express');
var router = express.Router();
// var mongoose = require('mongoose');
require('./../util/util')
var User = require('../models/user');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
/*
  查询当前用户 的购物车数据
  userId
*/
router.get('/cartList', (req, res, next) => {
  let userId = req.cookies.userId;

  User.findOne({ userId: userId }, (err, doc) => {
    if (err) {
      console.log(err)
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      if (doc) {
        res.json({
          status: '0',
          msg: '',
          result: doc.cartList
        })
      }
    }
  })
});
/*
  获取用户配送列表
*/

router.get("/addressList", (req, res, next) => {
  let userId = req.cookies.userId;
  console.log(userId)
  User.findOne({ userId: userId }, (err, doc) => {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {

      if (doc) {
        res.json({
          status: '0',
          msg: '',
          result: doc.addressList
        })
      } else {
        res.json({
          status: '1',
          msg: "用户不存在",
          result: '用户不存在'
        })
      }

    }
  })
});
/*

  登陆
*/

router.post('/login', (req, res, next) => {

  let param = {
    userName: req.body.params.userName,
    userPwd: req.body.params.userPwd
  }

  User.findOne(param, (err, doc) => {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      if (doc) {

        // 保存到cookie
        res.cookie("userId", doc.userId, {
          path: '/',
          maxAge: 1000 * 60 * 60
        })
        res.cookie("userName", doc.userName, {
          path: '/',
          maxAge: 1000 * 60 * 60
        })
        res.json({
          status: '0',
          msg: '',
          result: {
            userName: doc.userName
          }
        })

      } else {
        res.json({
          status: '1',
          msg: "用户名或密码错误"
        })
      }
    }
  })
});


/*退出*/

router.post('/logout', (req, res, next) => {
  res.cookie("userId", "", {
    path: '/',
    maxAge: -1
  })

  res.json({
    status: '0',
    msg: '',
    result: ''
  });
});

/*
  获取用户信息
*/
router.get('/checkLogin', (req, res, next) => {
  if (req.cookies.userId) {
    res.json({
      status: '0',
      msg: '',
      result: req.cookies.userName
    })
  } else {
    res.json({
      status: '1',
      msg: '',
      result: "当前未登陆"
    })
  }
});



/*删除 购物车*/
//productId = req.body.params.productId;
router.post('/delCart', (req, res, next) => {
  let userId = req.cookies.userId;
  let productId = req.body.params.productId;
  console.log(productId)
  console.log(userId)
  User.update({ userId: userId }, { $pull: { 'cartList': { 'productId': productId } } }, (err, doc) => {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })

    } else {
      res.json({
        status: '0',
        msg: '',
        result: '删除成功'
      })
    }
  });

});

/* 编辑购物车*/
router.post('/editCart', (req, res, next) => {
  let userId = req.cookies.userId;
  let productId = req.body.params.productId;
  let productNum = req.body.params.productNum;
  let checked = req.body.params.checked;

  User.update({
    'userId': userId,
    'cartList.productId': productId
  }, {
    'cartList.$.productNum': productNum,
    "cartList.$.checked": checked
  }, (err, doc) => {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      res.json({
        status: '0',
        msg: '',
        result: '编辑购物车成功'
      })
    }
  })
});

/* 全选 全不选*/

router.post('/editCartCheckedAll', (req, res, next) => {
  let userId = req.cookies.userId;
  let checkedAll = req.body.params.checkedAll ? '1' : '0';

  User.findOne({ userId: userId }, (err, user) => {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      if (user) {
        user.cartList.forEach((item) => {
          item.checked = checkedAll
        })

        user.save((checkedAllErr, doc) => {
          if (checkedAllErr) {
            res.json({
              status: '1',
              msg: err.message,
              result: ''
            })
          } else {
            res.json({
              status: '0',
              msg: '',
              result: '全选-全不选编辑成功'
            })
          }
        })

      }

    }
  })
});

/* 设置默认地址接口*/

router.post("/setDefauatAddress", (req, res, next) => {
  let userId = req.cookies.userId,
    addressId = req.body.addressId;

  if (!addressId) {
    res.json({
      status: '1003',
      msg: "addressId is null",
      result: ''
    })
  } else {
    User.findOne({ userId: userId }, (err, doc) => {
      if (err) {
        res.json({
          status: '1',
          msg: err.message,
          result: ''
        })
      } else {
        if (doc) {
          var addressList = doc.addressList

          addressList.forEach((item) => {
            if (item.addressId == addressId) {
              item.isDefault = true
            } else {
              item.isDefault = false
            }
          });

          doc.save((errSave, docSave) => {
            if (errSave) {
              res.json({
                status: '1',
                msg: err.message,
                result: ''
              })
            } else {
              res.json({
                status: '0',
                msg: "",
                result: ''
              })
            }
          })
        }
      }
    })
  }

})

/* 删除地址*/
router.post("/delAddress", (req, res, next) => {
  let userId = req.cookies.userId,
    addressId = req.body.addressId;

  if (!addressId) {
    res.json({
      status: '1003',
      msg: "addressId is null",
      result: ''
    })
  } else {
    User.update({ userId: userId }, { $pull: { 'addressList': { 'addressId': addressId } } }, (err, doc) => {
      if (err) {
        res.json({
          status: '1',
          msg: err.message,
          result: ''
        })

      } else {
        res.json({
          status: '0',
          msg: '',
          result: '删除成功'
        })
      }
    });
  }

})

/* 生成订单*/
router.post("/payMent", (req, res, next) => {
  let userId = req.cookies.userId,
    addressId = req.body.addressId,
    orderTotal = req.body.orderTotal;

  //查询用户信息  生成并保存 订单

  User.findOne({ userId: userId }, (err, uDoc) => {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })

    } else {
      if (uDoc) {
        //获取当前用户地址信息  和用户购买的商品  订单总金额
        let address = '',
          goodList = [];
        uDoc.addressList.forEach((item) => {
          if (addressId == item.addressId) {
            address = item
          }
        })

        // 获取用户购物车 购买的商品
        uDoc.cartList.filter((item) => {
          if (item.checked == '1') {
            goodList.push(item) // 保存用户已经购买的商品
          }
        })

        /*
        生成 orderId  和订单创建时间 createDate
        */
        let platform = '622'; // 平台码
        let r1 = Math.floor(Math.random() * 10); // 0-9 的随机数 1
        let r2 = Math.floor(Math.random() * 10);// 0-9 的随机数 2

        let sysDate = new Date().Format('yyyyMMddhhmmss'); // 系统时间
        let createDate = new Date().Format('yyyy-MM-dd hh:mm:ss');
        let orderId = platform + r1 + sysDate + r2;
        /*
            end
        */

        // 拿到用户地址信息  和购买的商品 
        // 开始创建订单
        const order = {
          orderId: orderId,
          orderTotal: orderTotal,
          addressInfo: address,
          goodList: goodList,
          orderStatus: '1', // 订单状态
          createDate: createDate // 创建时间
        }

        // 将订单 添加到集合中
        /*保存订单 start*/
        uDoc.orderList.push(order)

        uDoc.save((serr, sDoc) => {
          if (serr) {
            res.json({
              status: '1',
              msg: err.message,
              result: ''
            })
          } else {
            res.json({
              status: '0',
              mag: '',
              result: {
                orderId: order.orderId,
                orderTotal: order.orderTotal
              }
            })

          }
        })
        /*保存订单 end*/

      }

    }
  })
})

//根据订单Id查询订单信息
router.get("/orderDetail", function (req,res,next) {
  var userId = req.cookies.userId,orderId = req.param("orderId");
  User.findOne({userId:userId}, function (err,userInfo) {
      if(err){
          res.json({
             status:'1',
             msg:err.message,
             result:''
          });
      }else{
         var orderList = userInfo.orderList;
         if(orderList.length>0){
           var orderTotal = 0;
           orderList.forEach((item)=>{
              if(item.orderId == orderId){
                orderTotal = item.orderTotal;
              }
           });
           if(orderTotal>0){
             res.json({
               status:'0',
               msg:'',
               result:{
                 orderId:orderId,
                 orderTotal:orderTotal
               }
             })
           }else{
             res.json({
               status:'120002',
               msg:'无此订单',
               result:''
             });
           }
         }else{
           res.json({
             status:'120001',
             msg:'当前用户未创建订单',
             result:''
           });
         }
      }
  })
});


module.exports = router;
